/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BundleGenerator;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import javax.swing.JEditorPane;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.cookies.EditorCookie;
import org.openide.loaders.DataObject;
import org.openide.nodes.Node;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.TopComponent;




@ActionID(
        category = "Source",
        id = "BundleGenerator.BundleGenerator")
@ActionRegistration(
        displayName = "#CTL_BundleGenerator")
@ActionReferences({
    @ActionReference(path = "Menu/Source", position = 200),
    @ActionReference(path = "Shortcuts", name = "OS-G")
})
@Messages("CTL_BundleGenerator=Generete Bundle")
public final class BundleGenerator implements ActionListener {

    private final DataObject context; 
    
    public BundleGenerator(DataObject context) { 
        this.context = context; 
    } 
    
    @Override
    public void actionPerformed(ActionEvent e) {
        Node[] n = TopComponent.getRegistry().getActivatedNodes();
        if (n.length == 1) {
            EditorCookie ec = (EditorCookie) n[0].getCookie(EditorCookie.class);
            if (ec != null) {
                JEditorPane[] panes = ec.getOpenedPanes();
                if (panes.length > 0) {
                        if (panes[0].getSelectedText() != null) {
                            String postfixTypedByUser = javax.swing.JOptionPane.showInputDialog(this, "name");
                            if (postfixTypedByUser != null && !"".equals(postfixTypedByUser)) {
                                String selectedText = panes[0].getSelectedText();
                                String propertyName = generatePropertyName(postfixTypedByUser);
                                replaceTextInCode(panes[0], propertyName);
                                addPropertyToBundle(propertyName, selectedText);                                
                            }
                        }
                }
            }
        }
    }
    
    
    private String generatePropertyName(String postfixTypedByUser) {
        String currentFileName = context.getPrimaryFile().getName();
        String currentFileNameInSnakeCase = currentFileName.replaceAll("(.)(\\p{Lu})", "$1_$2").toLowerCase(); // fromCamelCase -> to_snake_case
        String propertyName = currentFileNameInSnakeCase + "__" + postfixTypedByUser; 
        return propertyName;
    }
    
    private void replaceTextInCode(JEditorPane pane, String bundleName) {
        String mimeType = pane.getEditorKit().getContentType(); 
        if (mimeType.startsWith("text/html")) {
            replaceTextInXhtml(pane, bundleName);
        }
        if (mimeType.startsWith("text/x-java")) {
            replaceTextInJavaCode(pane, bundleName);
        }
    }
    
    private void replaceTextInXhtml(JEditorPane pane, String bundleName) {
        String newText = "#{bundle."+bundleName+"}";
        pane.replaceSelection(newText);
    }
    
    private void replaceTextInJavaCode(JEditorPane pane, String bundleName) {
        String newText = "bundle.getString(\""+bundleName+"\")";
        pane.replaceSelection(newText);
    }
    
    
    private void addPropertyToBundle(String propertyName, String selectedText) {
        String bundleFilePath = "/home/dominik/NetBeansProjects/Ultimo/Ultimo-service/src/main/resources/bundle.properties";      
         
        Properties props = new Properties();
        props.setProperty(propertyName, selectedText);
        try {
            FileOutputStream out = new FileOutputStream(bundleFilePath, true); 
            ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
            props.store(arrayOut, null);
            String string = new String(arrayOut.toByteArray(), "8859_1");
            String sep = System.getProperty("line.separator");
            String content = string.substring(string.indexOf(sep), string.length()-sep.length());
            out.write(content.getBytes("8859_1"));
            out.close();
        } catch ( Exception e ) {
        }        
    }
    
}
